from odoo import fields, models, api


class InstructionCreateInvoiceWiz(models.Model):
    _name = 'instruct.create.invoice.wiz'
    _description = 'Create Invoice Wizard From Instruct Shipping'

    ship_instructions_id = fields.Many2one('ship.instructions', default=lambda self: self.env.context.get('default_ship_instructions_id', False))
    select = fields.Selection(string='Create Mode', selection=[
        ('standard', 'Standard'),
        ('po', 'Created for each PO'),
    ], default='standard')
    freight = fields.Boolean(string='Freight')

    def create_invoice(self):
        for rec in self.ship_instructions_id:
            if self.select == 'standard':
                # 创建发票
                invoice = self.env['account.move'].create({
                    'partner_id': rec.partner_id.id,
                    'invoice_payment_term_id': rec.sale_ids[0].payment_term_id.id,
                    'invoice_date': fields.Date.today(),
                    'currency_id': rec.sale_ids[0].currency_id.id,
                    'move_type': 'out_invoice',
                    's_instruction_num': rec.pd_id.name,
                    'journal_id': self.env['account.journal'].with_context(lang='zh_CN').search([('name', '=', '客户发票')]).id
                })
                for line in rec.line_ids:
                    if line.sale_order_line_id:
                        # 创建相应的发票行 (account.move.line)
                        move_line = self.env['account.move.line'].create({
                            'move_id': invoice.id,  # 关联到发票
                            'product_id': line.product_id.id,
                            'quantity': line.delivery_qty,
                            'price_unit': line.sale_order_line_id.price_unit,
                            'account_id': self.env['account.account'].search([('code', '=', '410000')]).id,
                            'product_uom_id': line.product_id.uom_id.id,
                            'tax_ids': line.sale_order_line_id.tax_id.ids,
                        })
                        line.sale_order_line_id.write({
                            'invoice_lines': [(4, move_line.id)]  # 将 move_line 关联到 Sale Order Line
                        })
                        for obj in line.sale_order_line_id.order_id.order_line:
                            if obj.product_id.detailed_type == 'service':
                                if obj.product_uom_qty == obj.qty_invoiced:
                                    break
                                else:
                                    nre_invoice = self.env['account.move.line'].create({
                                        'move_id': invoice.id,  # 关联到发票
                                        'product_id': obj.product_id.id,
                                        'quantity': obj.product_uom_qty,
                                        'price_unit': obj.price_unit,
                                        'account_id': self.env['account.account'].search([('code', '=', '410000')]).id,
                                        'product_uom_id': obj.product_id.uom_id.id,
                                        'tax_ids': obj.tax_id.ids,
                                    })
                                    obj.write({
                                        'invoice_lines': [(4, nre_invoice.id)]  # 将 move_line 关联到 Sale Order Line
                                    })
                self.ship_instructions_id.write({
                    'invoice_ids': [(4, invoice.id)]  # 使用(4, id)附加到 Many2many 字段
                })
                invoice.action_post()
                return invoice
            elif self.select == 'po':
                for line in rec.line_ids:
                    so = line.sale_order_id
                    invoice = self.env['account.move'].create({
                        'partner_id': so.partner_id.id,
                        'invoice_payment_term_id': so.payment_term_id.id,
                        'invoice_date': fields.Date.today(),
                        'currency_id': so.currency_id.id,
                        'move_type': 'out_invoice',
                        's_instruction_num': line.ship_instructions_id.pd_id.name,
                        'journal_id': self.env['account.journal'].with_context(lang='zh_CN').search([('name', '=', '客户发票')]).id
                    })
                    move_line = self.env['account.move.line'].create({
                        'move_id': invoice.id,  # 关联到发票
                        'product_id': line.product_id.id,
                        'quantity': line.delivery_qty,
                        'price_unit': line.sale_order_line_id.price_unit,
                        'account_id': self.env['account.account'].search([('code', '=', '410000')]).id,
                        'product_uom_id': line.product_id.uom_id.id,
                        'tax_ids': line.sale_order_line_id.tax_id.ids,
                    })
                    line.sale_order_line_id.write({
                        'invoice_lines': [(4, move_line.id)]  # 将 move_line 关联到 Sale Order Line
                    })
                    for obj in line.sale_order_line_id.order_id.order_line:
                        if obj.product_id.detailed_type == 'service':
                            if obj.product_uom_qty == obj.qty_invoiced:
                                break
                            else:
                                nre_invoice = self.env['account.move.line'].create({
                                    'move_id': invoice.id,  # 关联到发票
                                    'product_id': obj.product_id.id,
                                    'quantity': obj.product_uom_qty,
                                    'price_unit': obj.price_unit,
                                    'account_id': self.env['account.account'].search([('code', '=', '410000')]).id,
                                    'product_uom_id': obj.product_id.uom_id.id,
                                    'tax_ids': obj.tax_id.ids,
                                })
                                obj.write({
                                    'invoice_lines': [(4, nre_invoice.id)]  # 将 move_line 关联到 Sale Order Line
                                })
                    self.ship_instructions_id.write({
                        'invoice_ids': [(4, invoice.id)]  # 使用(4, id)附加到 Many2many 字段
                    })
                    invoice.action_post()
